<script setup lang="ts">
import type { TreeProps } from 'ant-design-vue';

import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { StepExecutionModel } from '#/api/production/models';

import { onMounted, reactive, ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { downloadFileFromUrl } from '@vben/utils';

import { Button, Card, Flex, Tooltip, Tree } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getAllLineListApi } from '#/api/master/line';
import {
  downloadAllExcelApiUrl,
  downloadExcelApiUrl,
  getProcessStepPagedListApi,
} from '#/api/traceability/workstationProcessQuery';

import StepTaskDataDrawer from '../product/modules/step-task-data-drawer.vue';
import { useColumns, useSearchSchema } from './data';

const state = reactive({
  lineId: 0,
  workstationId: 0,
  formValues: null,
});
const treeData = ref<TreeProps['treeData']>([]);

const [DataDrawer, dataDrawerApi] = useVbenDrawer({
  connectedComponent: StepTaskDataDrawer,
  destroyOnClose: true,
});

/**
 * 显示数据
 */
function onOpen(row: StepExecutionModel) {
  dataDrawerApi.setData(row).open();
}

/**
 * 导出数据
 */
function onExport(row: StepExecutionModel) {
  downloadFileFromUrl({
    source: downloadExcelApiUrl({ stepExecutionId: row.id }),
    target: '_self',
  });
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<StepExecutionModel>) {
  switch (code) {
    case 'export': {
      onExport(row);
      break;
    }
    case 'open': {
      onOpen(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    collapsed: true,
    fieldMappingTime: [['rangeDate', ['startTime', 'endTime']]],
    schema: useSearchSchema(),
    // 控制表单是否显示折叠按钮
    showCollapseButton: true,
    submitOnEnter: true,
  },
  gridOptions: {
    columns: useColumns(onActionClick),
    border: true,
    stripe: true,
    pagerConfig: {},
    toolbarConfig: {
      custom: true,
      refresh: true,
      resizable: true,
      zoom: true,
    },
    proxyConfig: {
      autoLoad: false,
      ajax: {
        query: async ({ page }, formValues) => {
          state.formValues = formValues;
          return await getProcessStepPagedListApi({
            pageNumber: page.currentPage,
            pageSize: page.pageSize,
            lineId: state.lineId,
            workstationId: state.workstationId,
            ...formValues,
          });
        },
      },
    },
  } as VxeTableGridOptions,
});

/**
 * 导出筛选出的所有数据
 */
async function downloadAllExcel() {
  downloadFileFromUrl({
    source: downloadAllExcelApiUrl(
      Object.assign({}, state.formValues, {
        lineId: state.lineId,
        workstationId: state.workstationId,
      }),
    ),
    target: '_self',
  });
}

const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
  state.workstationId = (selectedKeys[0] ?? 0) as number;
  state.lineId = (info.node.parent?.key ?? 0) as number;
  gridApi.grid.remove(); // 清空数据
};

onMounted(async () => {
  const lines = await getAllLineListApi();
  treeData.value = lines.map((line) => ({
    key: line.id,
    title: line.lineName,
    selectable: false,
    children: line.workstations?.map((workstation) => ({
      key: workstation.id,
      title: `${workstation.wsCode} (${workstation.wsName})`,
      isLeaf: true,
    })),
  }));
});
</script>

<template>
  <Page auto-content-height>
    <DataDrawer />
    <Flex class="h-full w-full">
      <div class="h-full w-3/12">
        <Card class="h-full overflow-auto" size="small" title="生产线">
          <Tree :tree-data="treeData" block-node @select="onSelect" />
        </Card>
      </div>
      <div class="ml-2 h-full w-9/12">
        <Grid>
          <template #toolbar-tools>
            <Tooltip color="cyan" title="数据导出前请先查询数据">
              <Button
                :disabled="!state.workstationId"
                @click="downloadAllExcel"
              >
                数据导出
              </Button>
            </Tooltip>
          </template>
        </Grid>
      </div>
    </Flex>
  </Page>
</template>
